<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>菜单权限</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-form :inline="true" :model="userKeyWord" class="demo-form-inline">
        <el-form-item label-width="70px">
          <el-input clearable :changeValue="changeValue" v-model="userKeyWord.keyWord" placeholder="输入关键字进行过滤" style="width: 547px"></el-input>
        </el-form-item>
        <el-form-item style="margin-left: 10px">
          <el-button type="primary" icon="el-icon-plus" @click="add">父级</el-button>
<!--          <el-button icon="el-icon-download" @click="exportDown">导出</el-button>-->
        </el-form-item>
      </el-form>
      <el-tree
        :data="menuTree"
        show-checkbox
        node-key="id"
        :default-expanded-keys="defaultExpandKeys"
        :expand-on-click-node="false">
          <template #default="{ data }">
            <span class="custom-tree-node">
              <el-row :gutter="20">
                  <el-col :span="6">
                    <div class="grid-content-menu">
                      <span :class="data.icon">&nbsp;&nbsp;{{ data.menuName }}</span>
                      <span>&nbsp;&nbsp;<el-button class="grid-content-button" v-if="data.type===0" size="mini" type="primary" plain>菜单</el-button><el-button class="grid-content-button" v-else type="warning" size="mini" plain>权限[{{data.perms }}]</el-button></span>
                    </div>
                  </el-col>
              </el-row>
              <span>
                <el-button size="mini" type="text" icon="el-icon-edit" @click="editMenu(data.id)">编辑</el-button>
                <el-button size="mini" type="text" icon="el-icon-plus" v-if="data.type===0" @click="addMenuData(data)">增加</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteMenus(data.id)">删除</el-button>
              </span>
            </span>
          </template>
      </el-tree>
      <!-- 添加对话框 -->
      <el-dialog :title="formTitle === 'add' ? '添加菜单' : '编辑菜单'" :visible.sync="addDialogVisible" width="50%" @close="editClose">
        <span>
          <el-form
            :model="editForm"
            :label-position="labelPosition"
            :rules="addFormRules"
            ref="editFormRef"
            label-width="80px"
          >
            <el-row>
              <el-col :span="20">
                <div class="grid-content bg-purple">
                  <el-form-item label="菜单名称" prop="menuName">
                    <el-input v-model="editForm.menuName"></el-input>
                  </el-form-item>
                </div>
              </el-col>
               <el-col :span="20">
                <div class="grid-content bg-purple">
                  <el-form-item label="父级菜单" prop="parentId">
                    <el-input v-if=" this.addtype == '0'" v-model="editForm.parentId" disabled></el-input>
                    <el-input v-else v-model="this.parentName" disabled></el-input>
                  </el-form-item>
                </div>
              </el-col>
               <el-col :span="20">
                <div class="grid-content bg-purple">
                  <el-form-item label="菜单URL" prop="url">
                    <el-input v-model="editForm.url"></el-input>
                  </el-form-item>
                </div>
              </el-col>
               <el-col :span="20">
                <div class="grid-content bg-purple">
                  <el-form-item label="菜单权重" prop="perms">
                    <el-input v-model="editForm.perms"></el-input>
                  </el-form-item>
                </div>
              </el-col>
                <el-col :span="20">
                <div class="grid-content bg-purple">
                  <el-form-item label="菜单Icon" prop="icon">
                    <el-input v-model="editForm.icon"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="10">
                 <el-form-item label="是否展开" prop="open">
                    <el-radio-group v-model="editForm.open">
                      <el-radio :label="0">否</el-radio>
                      <el-radio :label="1">是</el-radio>
                    </el-radio-group>
                 </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="类型" prop="type">
                    <el-radio-group v-model="editForm.type">
                      <el-radio :label="0">菜单</el-radio>
                      <el-radio :label="1">按钮</el-radio>
                    </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="addMenu"
            :loading="btnLoading"
            :disabled="btnDisabled"
          >确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { addMenu, queryMenuList, edit, updataMenu,  deleteMenu } from '@/api/Users'

export default {
  name: 'Menus',
  data(){
    return {
      userKeyWord: {
        keyWord: "",
        type:""
      },
      menuTree:[],
      defaultExpandKeys:[], //默认展开的数据
      addDialogVisible:false ,  //添加对话框
      editForm: {
        open :1,   //展开
        type :0  //菜单
      } ,
      labelPosition: "right", //lable对齐方式
      addFormRules: {
        menuName: [
          { required: true, message: "请输入菜单名称", trigger: "blur" },
          { min: 1, max: 50, message: "长度不能超过 50 个字符", trigger: "blur" }
        ],
        icon: [
        { required: true, message: "请输入菜单Icon", trigger: "blur" },
        { min: 1, max: 50 ,message: "长度不能超过 50 个字符", trigger: "blur" }
      ]
      }, //添加表单验证规则
      btnLoading: false,
      btnDisabled: false,
      addtype :0 ,   //0:新增父级根节点  1 :新增菜单
      parentName :'',
      formTitle :''
    }
  },
  methods:{
    /**
     * 菜单列表
     * @returns {Promise<void>}
     */
    async queryMenuList(){
      const {data:res} =await queryMenuList(this.userKeyWord);
      if (res.code==200){
        console.log(res.data.menuList);
        this.menuTree=res.data.menuList;
        //把需要展开的id放进defaultExpandKeys
        this.getAllNodeId(this.defaultExpandKeys,res.data.menuList);
        console.log(this.defaultExpandKeys)
      }else {
        this.$message.error( res.message);
      }
    },
    /**
     * 获取默默认节点id
     * @param expandedKeys
     * @param moduleDataList
     * @returns {*}
     */
     getAllNodeId (expandedKeys, moduleDataList) {
      for (let i = 0; i < moduleDataList.length; i++) {
        if (moduleDataList[i].open==1){
          expandedKeys.push(moduleDataList[i].id)
        }
        if (moduleDataList[i].children) {
          expandedKeys = this.getAllNodeId(expandedKeys, moduleDataList[i].children)
        }
      }
      return expandedKeys
    },
    async deleteMenus(id){
      var res = await this.$confirm(
        "此操作将永久删除该菜单, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
      if (res == "confirm"){
        const { data: res } =await deleteMenu(id)
        console.log(res)
        if (res.code == 200) {
          this.$notify.success({
            title:'操作成功',
            message:'菜单删除成功',
          });
          this.queryMenuList(this.userKeyWord);
        } else {
          this.$message.error(res.message);
        }
      }
    },
    async editMenu(id){
      this.formTitle ='edit'
      const { data: res } = await edit(id)
      if (res.code == 200) {
        console.log(res.data.menuDetail)
        this.editForm = res.data.menuDetail;
        if (this.editForm.parentId == 0){
          this.addtype=0
        }else {
          this.addtype=1
          this.getParentName(this.editForm,this.menuTree)
        }
        this.addDialogVisible = true;
      }else {
        this.$message.error(res.message);
      }
    },
    //遍历查询父级菜单名字
    getParentName(detailList,parentDetail){
      for (let i = 0; i < parentDetail.length; i++) {
        if (parentDetail[i].id == detailList.parentId){
          this.parentName = parentDetail[i].menuName
          return;
        }
        if (parentDetail[i].children){
          this.getParentName(detailList,parentDetail[i].children)
        }
      }
    },
    async addMenuData(data){
      this.editForm.parentId =data.id,
      this.parentName=data.menuName,
      this.addtype=1,
      this.editForm.type = 0,//  菜单
      this.editForm.open =1 ,//默认展开
      this.formTitle ='add',
      this.addDialogVisible = true,
        console.log(this.editForm)
    },
    /**
     * 关闭编辑弹出框
     */
    editClose() {
      this.$refs.editFormRef.clearValidate();
      this.editForm = {open :1,   //展开
        type :0 };
    },
    // 按钮点击事件 显示新增弹窗组件
    add(){
      this.addtype=0,
      this.editForm.parentId =0,//根节点
      this.editForm.type = 0,//  菜单
      this.editForm.open =1 ,//默认展开
      this.addDialogVisible = true
    },

    async addMenu(){
      this.$refs.editFormRef.validate(async valid =>{
        if (!valid){
          return;
        }else {
          this.btnLoading = true;
          this.btnDisabled = true;
          if (this.formTitle === 'add'){ //添加菜单
            const { data: res} =await addMenu(this.editForm)
            if (res.code=='200'){
              this.$notify.success({
                title: '操作成功',
                message: '菜单添加成功',
              })
              this.editForm = {};
              this.queryMenuList(this.userKeyWord);
            }else {
              this.$message.error(res.message);
            }
          }else {  //编辑菜单
            this.editForm.createTime=''
            this.editForm.modifiedTime=''
            const { data: res} =await updataMenu(this.editForm)
            if (res.code=='200'){
              this.$notify.success({
                title: '操作成功',
                message: '菜单修改成功',
              })
              this.editForm = {};
              this.queryMenuList(this.userKeyWord);
            }else {
              this.$message.error(res.message);
            }
          }

          this.addDialogVisible = false;
          this.btnLoading = false;
          this.btnDisabled = false;
        }
      });
    }
  },
  //computed用来监控自己定义的变量
  computed:{
    /**
     * 声名变量changeValue，边输边搜索
     * @param e
     */
    changeValue:function (e){
      this.queryMenuList(this.userKeyWord)
    }
  }
}
</script>

<style lang="less" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.grid-content-button{
  padding-bottom: 3px;
  padding-top: 3px;
  padding-left: 5px;
  padding-right: 5px;
}
</style>
